package cn.Leamus;

/*import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Button;*/

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.app.PendingIntent;
import android.widget.Toast;
import android.os.Message;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.location.LocationManager;
import android.location.Criteria;
import android.provider.Settings;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import java.lang.ClassLoader;
import dalvik.system.DexClassLoader;
import java.lang.reflect.Field;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import android.provider.MediaStore;
import java.lang.String;
import android.util.Log;

/*
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.JumpToOfflinePay;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;





import android.webkit.WebView;
*/


import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;

import cn.Leamus.alipay.util.OrderInfoUtil2_0;
import cn.Leamus.alipay.PayResult;

import android.view.View;
import android.text.TextUtils;
import java.util.Map;
import android.os.Handler;

/**
 *  重要说明：
 *
 *  本 Demo 只是为了方便直接向商户展示支付宝的整个支付流程，所以将加签过程直接放在客户端完成
 *  （包括 OrderInfoUtil2_0_HK 和 OrderInfoUtil2_0）。
 *
 *  在真实 App 中，私钥（如 RSA_PRIVATE 等）数据严禁放在客户端，同时加签过程务必要放在服务端完成，
 *  否则可能造成商户私密数据泄露或被盗用，造成不必要的资金损失，面临各种安全风险。
 *
 *  Warning:
 *
 *  For demonstration purpose, the assembling and signing of the request parameters are done on
 *  the client side in this demo application.
 *
 *  However, in practice, both assembling and signing must be carried out on the server side.
 */








public class Alipay {

    //构造函数
    public Alipay() {
        //m_instance = this;

        Log.i("[java]Qt Java Example By Pleafles", "Alipay");
        Log.d("[java]Qt Java Example By Pleafles", "Alipay");
        //GetQtVersion();
    }




    //Toast貌似必须运行在主线程里!?
    //一种实现Toast的方法
    public static void QMessage(String s)
    {
        m_instance.QMessage(s);
    }





//成员变量
    public static MainActivity m_instance;     //保存实例（供静态方法是用）







    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static String APPID = "2018071960687460";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static String PID = "2088231013063902";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static String TARGET_ID = "";

    /**
     *  pkcs8 格式的商户私钥。
     *
     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * 	RSA2_PRIVATE。
     *
     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static String RSA2_PRIVATE = "MIIEowIBAAKCAQEAwxAQDZmRHVmbRVwpPwSvhQcg64TOlBvMwCsfPIOxTiMNKsZIqtp8FQ/Yx9rbV/6NwsXh7jBeDQ+uJEp6kxC/0soxf1+XB3kLZhbrzMT+WD4Z19Eja2zBf2vDJWcxX0CNhrEpgMTYwM4CnTum2EGT5F225DXtJtTppmtCax0UDM+OEOjSmgLp71WN1NaD7jPpX3S/TNASzOAiloEdRfgnHGt7LmCQja+1vkv5upw5MHK/sxPuzMiszFGjIERZO93FpsteCCYmMPuCroi3dr63ImHaEmX5N4j3jqP9wLD+PeGgahA6Hdw6MBF5ht1R3mX+k8E4j6KsnmUbCDkfC0aLywIDAQABAoIBAASnsXphm9Dzfn0dQe67EeU+0k5MkRF/yFcdsFUlX2nZ9Ep9CObq5+MoyaebVXi4HnHzfvzMMrJlGWbMUDiKQcmqAZxkj5oiDV+WVHJCkT9R3BQGba32nneH/tQ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JFsE+rRjeBRDwgj3rcnSn4b";
    public static String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;


    public static void setAlipayInfo(String appId,
                                    String pId,
                                    String targetId,
                                    String rsa2Private,
                                    String rsaPrivate
                                    ) {
        APPID = appId;
        PID = pId;
        TARGET_ID = targetId;
        RSA2_PRIVATE = rsa2Private;
        RSA_PRIVATE = rsaPrivate;
    }


    //@SuppressLint("HandlerLeak")
    private static Handler mHandler = new Handler() {
            //@SuppressWarnings("unused")
            public void handleMessage(Message msg) {
                    switch (msg.what) {
                    case SDK_PAY_FLAG: {
                            //@SuppressWarnings("unchecked")
                            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                            /**
                             * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                             */
                            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                            String resultStatus = payResult.getResultStatus();
                            // 判断resultStatus 为9000则代表支付成功
                            if (TextUtils.equals(resultStatus, "9000")) {
                                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                                    // showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
                                    QMessage("支付成功：" + payResult);
                            } else {
                                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                                    // showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                                    QMessage("支付失败：" + payResult);
                            }
                            break;
                    }
                    /*case SDK_AUTH_FLAG: {
                            //@SuppressWarnings("unchecked")
                            AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                            String resultStatus = authResult.getResultStatus();

                            // 判断resultStatus 为“9000”且result_code
                            // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                            if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                                    // 获取alipay_open_id，调支付时作为参数extern_token 的value
                                    // 传入，则支付账户为该授权账户
                                    // showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
                            } else {
                                    // 其他状态值则为授权失败
                                    // showAlert(PayDemoActivity.this, getString(R.string.auth_failed) + authResult);
                            }
                            break;
                    }*/
                    default:
                            break;
                    }
            };
    };

    /**
     * 获取支付宝 SDK 版本号。
     */
    public static void showSdkVersion() {
            PayTask payTask = new PayTask(m_instance);
            //showAlert(this, getString(R.string.alipay_sdk_version_is) + version);
            String version = payTask.getVersion();
            QMessage("Alipay SDK version: " + version);
    }

    /**
     * 支付宝支付业务示例
     */
    public static void payV2(float total_amount, int timeout_express, String body) {
            if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
                    //showAlert(this, getString(R.string.error_missing_appid_rsa_private));
                    QMessage("Error: Missing \"APPID\" or \"RSA_PRIVATE\" in PayDemoActivity.");
                    return;
            }

            /*
             * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
             * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
             * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
             *
             * orderInfo 的获取必须来自服务端；
             */
            boolean rsa2 = (RSA2_PRIVATE.length() > 0);
            Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, total_amount, timeout_express, body);
            String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

            String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
            String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
            final String orderInfo = orderParam + "&" + sign;


            Log.i("orderParam:", orderParam);
            Log.i("sign:", sign);
            Log.i("orderInfo:", orderInfo);


            final Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                            PayTask alipay = new PayTask(m_instance);
                            Map<String, String> result = alipay.payV2(orderInfo, true); //阻塞，调用 支付宝

                            Log.i("msp", result.toString());

                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                    }
            };

            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
    }


}
